//
//  HEGoodsDetailsTabBar.m
//  HealthElderly
//
//  Created by 吴欧 on 2020/10/23.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEGoodsDetailsTabBar.h"
#import "HECollectionPlatformRequest.h"
#import "HECollectionMallRequest.h"
#import "HEAddCartRequest.h"

@interface HEGoodsDetailsTabBar ()

@property(nonatomic, strong) UIImageView *collectionView;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;

// 防止多次点击收藏
@property (nonatomic, assign) BOOL isFisnshCollReq;

/// 加入购物车按钮
@property (nonatomic, strong) UIButton *addCarBtn;

/// 立即购买 / 预约 按钮
@property (nonatomic, strong) UIButton *buyBt;

/// 购物车按钮
@property (nonatomic, strong) UIView *cartBtn;

/// 收藏按钮
@property (nonatomic, strong) UIView *collectBtn;

@end

@implementation HEGoodsDetailsTabBar

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self initUI];
        self.backgroundColor = UIColor.whiteColor;
        _isFisnshCollReq = YES;
        _barType = HEGoodsDetailsTabBarTypeOnlyBuy;
        
        self.qmui_borderPosition = QMUIViewBorderPositionTop;
        self.qmui_borderColor = KHexColor(@"F5F5F5");
    }
    return self;
}

- (void)initUI {
    
    NSArray *imagesNor = @[@{@"name":@"购物车",@"icon":@"good_detail_shop_car"},@{@"name":@"收藏",@"icon":@"collection_normal"}];
 
 
    NSMutableArray *btnArr = [NSMutableArray array];
    for (NSInteger i = 0; i < imagesNor.count; i++) {
        NSDictionary *dic = imagesNor[i];
        
        UIView *btnWarp = [UIView new];
        [self addSubview:btnWarp];
        
        UIImageView *icon = [UIImageView new];
        icon.image = IMAGE_NAMED(dic[@"icon"]);
        icon.contentMode = UIViewContentModeScaleAspectFit;
        [btnWarp addSubview:icon];

        UILabel *titleLb = [UILabel new];
        titleLb.text = dic[@"name"];
        titleLb.font = DYFont(12);
        titleLb.textColor = KHexColor(@"757575");
        [btnWarp addSubview:titleLb];
 
        [icon mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(btnWarp);
            make.width.mas_offset(20);
            make.height.mas_offset(20);
            make.top.equalTo(btnWarp);
        }];
        
        if (i == 1) { // 收藏
            _collectBtn = btnWarp;
            _collectionView = icon;
        }else {
            _cartBtn = btnWarp;
        }
        
        [titleLb mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(btnWarp);
            make.top.equalTo(icon.mas_bottom).mas_offset(5);
            make.height.mas_offset(12);
         }];
        [titleLb setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
        
        [btnArr addObject:btnWarp];
        
        [btnWarp mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self);
            make.top.equalTo(self).mas_offset(5);
            make.width.mas_offset(40);
            make.height.mas_offset(49);

            if (i == 0) {
                make.left.equalTo(self).mas_offset(15);
            }else {
                UIView *last = btnArr[i-1];
                make.left.equalTo(last.mas_right).mas_offset(10);
            }
        }];
        
        btnWarp.tag = i;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(btnClick:)];
        [btnWarp addGestureRecognizer:tap];
    }
 
    // 立即购买
    UIButton *buyBt = [UIButton buttonWithType:UIButtonTypeCustom];
    _buyBt = buyBt;
    [self addSubview:buyBt];
    
    NSString *buyTitle = _barType == HEGoodsDetailsTabBarTypeAppointment ? @"预约" : @"立即购买";

    [buyBt setTitle:buyTitle forState:UIControlStateNormal];
    buyBt.titleLabel.font = DYBlodFont(16);
    buyBt.backgroundColor = KHexColor(@"#3E8BF8");
    [buyBt setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
 
    CGFloat btnH = 39;
    CGFloat btnW = 110;

    buyBt.layer.masksToBounds = YES;
    buyBt.layer.cornerRadius = btnH / 2.0;
 
    [buyBt mas_makeConstraints:^(MASConstraintMaker *make) {
       make.top.equalTo(self).mas_offset(5);
       make.width.mas_offset(btnW);
       make.height.mas_offset(btnH);
       make.right.equalTo(self).mas_offset(-15);
   }];
    
    [buyBt addTarget:self action:@selector(buyClick) forControlEvents:UIControlEventTouchUpInside];
    
    // 加入购物车
    UIButton *addCarBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _addCarBtn = addCarBtn;
    [self addSubview:addCarBtn];

    [addCarBtn setTitle:@"加入购物车" forState:UIControlStateNormal];
    addCarBtn.titleLabel.font = DYBlodFont(16);
    addCarBtn.backgroundColor = KHexColor(@"#F67605");
    [addCarBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];

    addCarBtn.layer.masksToBounds = YES;
    addCarBtn.layer.cornerRadius = btnH / 2.0;

    [addCarBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(buyBt);
        make.width.mas_offset(btnW);
        make.height.mas_offset(btnH);
        make.right.equalTo(buyBt.mas_left).mas_offset(-10);
    }];
    
    [addCarBtn addTarget:self action:@selector(addCartClick) forControlEvents:UIControlEventTouchUpInside];
}

#pragma mark -
- (void)setBarType:(HEGoodsDetailsTabBarType)barType {
    _barType = barType;
    NSString *buyTitle = @"立即购买";
    if (_barType == HEGoodsDetailsTabBarTypeNomarl) {
        _addCarBtn.hidden = NO;
    }else if (_barType == HEGoodsDetailsTabBarTypeAppointment) {
        _addCarBtn.hidden = YES;
        buyTitle = @"预约";
    }else if (_barType == HEGoodsDetailsTabBarTypeOnlyBuy) {
        _addCarBtn.hidden = YES;
    }
    [_buyBt setTitle:buyTitle forState:UIControlStateNormal];
}

- (void)setShowCart:(BOOL)showCart {
    _showCart = showCart;
    
    if (showCart) {
        
    }else {
        _cartBtn.hidden = YES;
        
        [_collectBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(self);
            make.top.equalTo(self).mas_offset(5);
            make.width.mas_offset(40);
            make.height.mas_offset(49);

            make.left.equalTo(self).mas_offset(15);
        }];
    }
}

- (void)btnClick:(UITapGestureRecognizer *)tap {
    UIView *view = tap.view;
    NSInteger tag = view.tag;
    
    switch (tag) {
        case 0:
            {
                if([_delegate respondsToSelector:@selector(toCartPageHandler)]){
                    [_delegate toCartPageHandler];
                }
            }
            break;
        case 1:{
            // 收藏动作
            [self changeCollectStatusRequest];
        }
            break;
            
        default:
            break;
    }
}

#pragma mark - 收藏请
- (void)changeCollectStatusRequest {
 
    if (_isFisnshCollReq) {
        [self collectMallRequest];
    }
}

- (void)collectMallRequest {
    _isFisnshCollReq = NO;
    HECollectionMallRequest *request = [HECollectionMallRequest new];
    request.meno2 = _goods.sale;
    request.meno1 = _goods.price;
    request.objId = _goods.id;
    request.name = _goods.name;
    request.type = 1; // 收藏类别 1：商品 2：文章 3 店铺

    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrlByKeyValue:KServerUrl suffixUrl:KfavoriteSave parameters:request success:^(id  _Nonnull responseObject) {
      HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];
        if (response.success) {
            
            if (!self.isFavorite) {
                [self addCollectPlatRequest];
            }else{
                [self cancleCollectPlatRequest];
            }
        }
    } failure:^(NSError * _Nonnull error) {
        self.isFisnshCollReq = YES;
    }];
}

- (void)addCollectPlatRequest {
    HECollectionPlatformRequest *request = [HECollectionPlatformRequest new];
    request.product_id = _goods.id;
    request.product_icon = _goods.pic;
    request.product_price = _goods.price;
    request.product_name = _goods.name;
 
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KsaveProductCollection parameters:request success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];

        self.isFisnshCollReq = YES;
        if (response.success) {
            self.isFavorite = !self.isFavorite;
        }

    } failure:^(NSError * _Nonnull error) {
        self.isFisnshCollReq = YES;
    }];
}

- (void)cancleCollectPlatRequest {
    HECollectionPlatformRequest *request = [HECollectionPlatformRequest new];
    request.product_id = _goods.id;
    request.product_icon = _goods.pic;
    request.product_price = _goods.price;
    request.product_name = _goods.name;
    
    [WOAFNetWorkingHandle POSTNoHUDWithBaseUrl:KServerUrl suffixUrl:KcancelProductCollection parameters:request success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];

        self.isFisnshCollReq = YES;
        if (response.success) {
            self.isFavorite = !self.isFavorite;
        }

    } failure:^(NSError * _Nonnull error) {
        self.isFisnshCollReq = YES;
    }];
}

- (void)setIsFavorite:(BOOL)isFavorite {
    _isFavorite = isFavorite;
    
    if (isFavorite) {
        [self setupSelectCollectionIcon];
    }else {
        [self setupNoCollectionIcon];
    }
}

- (void)setupSelectCollectionIcon {
    _collectionView.image = IMAGE_NAMED(@"collection_sel");
}

- (void)setupNoCollectionIcon {
    _collectionView.image = IMAGE_NAMED(@"collection_normal");
}

#pragma mark - 加入购物车 立即购买

- (void)buyClick {
    if([_delegate respondsToSelector:@selector(buyNowHandler)]){
        [_delegate buyNowHandler];
    }
}

- (void)addCartClick {
    if([_delegate respondsToSelector:@selector(addCartHandler)]){
        [_delegate addCartHandler];
    }
}

@end
